<?php
namespace control;
/*
*食堂评价类
*/

class canteenEvaluateClass extends adIndexClass
{
    private const page = 'canteenEvaluate';
    private const table = 'dining_hall_ass';
    private const title = '食堂评价';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'hall'          => [
                        'name'  => '食堂名称',
                        'width' => 200,
                    ],
                    'recordDate' => [
                        'name'  => "日期",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'mealType'  => [
                        'name'  => "餐别",
                        'width' => 200,
                    ],
                    'menu'         => [
                        'name'  => '菜谱',
                        'width' => 200,
                    ],
                    'satisfaction'          => [
                        'name'  => '满意度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '评价意见',
                        'width' => 200,
                    ],
                    'stid'          => [
                        'name'  => '评价人',
                        'width' => 200,
                    ],
                    'time'          => [
                        'name'  => '评价时间',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "食堂名称" => selectMultiple(array("name" => "hallId","class" => "width200", 'table' => "dining_hall", 'sqlId' => 'id', 'sqlField' => 'name')),
                    "餐别"     => select(array("name" => "mealType", "option" => explode("，", para("mealOption")))),
                    '日期' => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    '评价意见'   => text(array("name" => "text")),
                    "满意度" => select(array("name" => "satisfaction",'option'=> explode('，', para('hallEvaluateOption')))),
                    '评价日期'   => text(array("name" => "creatime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button ='';
        if ($this->power(self::page,'export')){
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "text" => $this->post('text'),
        );
        //全等查询数组
        $equal = array(
            "mealType" => $this->post('mealType'),
            "orderId" => $this->post('hallId'),
            "satisfaction" => $this->post('satisfaction'),
        );
        $and = '';
        if ($this->post('time')){
            $and.=self::timeComparison($this->post('time'),field: 'recordDate');
        }
        if ($this->post('creatime')){
            $and.=self::timeComparison($this->post('creatime'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)).$and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        static::rSet(self::$stid.self::page. 'sql', $page['fullSql']);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "hall":
                        $hall = query('dining_hall',"id = '$array[orderId]'");
                        $row[] = $hall['name'];
                        break;
                    case "menu":
                        $menu = find(array('table'=>"dining_week_menu as a join dining_week_menu_detail as b on a.id = b.orderId join dining_menu as c on b.menuId = c.id",'field'=>"group_concat(c.name) as name",'single'=>"a.hallId = '$array[orderId]' and b.localDate = '$array[recordDate]' and b.mealType = '$array[mealType]'"));
                        $row[] = $menu['name'];
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button ='';
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by recordDate desc,time desc",
                ))['array'];
            }else{
                $sql = static::rGet(self::$stid.self::page . 'sql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $hall = query('dining_hall',"id = '$array[orderId]'");
                $menu = find(array('table'=>"dining_week_menu as a join dining_week_menu_detail as b on a.id = b.orderId join dining_menu as c on b.menuId = c.id",'field'=>"group_concat(c.name) as name",'single'=>"a.hallId = '$array[orderId]' and b.localDate = '$array[recordDate]' and b.mealType = '$array[mealType]'"));
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '食堂名称'=>$hall['name'],
                            '日期'=>$array['recordDate'],
                            '餐别'=>$array['mealType'],
                            '菜谱'=>$menu['name'],
                            '满意度'=>$array['satisfaction'],
                            '评价意见'=>$array['text'],
                            '评价人'=>self::findStaff($array['stid']),
                            '评价时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'食堂名称',
                    'aliasName'=>'食堂名称',
                ],
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'餐别',
                    'aliasName'=>'餐别',
                ],
                [
                    'columnName'=>'菜谱',
                    'aliasName'=>'菜谱',
                ],
                [
                    'columnName'=>'满意度',
                    'aliasName'=>'满意度',
                ],
                [
                    'columnName'=>'评价意见',
                    'aliasName'=>'评价意见',
                ],
                [
                    'columnName'=>'评价人',
                    'aliasName'=>'评价人',
                ],
                [
                    'columnName'=>'评价时间',
                    'aliasName'=>'评价时间',
                ],
            ]
        };
    }
}

